const fnDebugLog = require('debug')('decorator')

export const Controller = (root: string) => 
(target:any) => {
  fnDebugLog('!!!!! decorator', target)
  target.prototype.root = root;
}

export const Get = (route?:string) => 
(target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
  if (!target.handlersOfGet) target.handlersOfGet = []
  target.handlersOfGet.push({
    route: route ?? '',
    method: propertyKey
  })
  const fnMethod = descriptor.value;
  descriptor.value = function (...args:any[]) {
    console.log('++++++', args, propertyKey, fnMethod);
    const paramDef = (this as any)[`paramFor${propertyKey}`]
    console.log(paramDef, paramDef?.length)

    let result = null
    try {
      const newArgs = [ ...args ];
      if (paramDef?.length) {
        paramDef.forEach((fieldName: string, index: number) => {
          console.log(fieldName)
          if (!!fieldName?.length) {
            newArgs[index] = !fieldName[1] ? args[0]?.[fieldName[0]] : args[0]?.[fieldName[0]]?.[fieldName[1]];
          }
        });
      }
      result = fnMethod.apply(this, newArgs);
    }
    catch (err) {
      console.error(err)
    }
    finally {
      console.log('------');
      return result
    }
  }
}

export const Head = (fieldName?:string) => 
(target: any, methodName: string, parameterIndex: number) => {
  // console.log('@Head', methodName, parameterIndex, fieldName);
  if (!target[`paramFor${methodName}`]) target[`paramFor${methodName}`] = []
  target[`paramFor${methodName}`][parameterIndex] = !fieldName ? ['head'] : ['head', fieldName];
}

export const Params = (fieldName?:string) => 
(target: any, methodName: string, parameterIndex: number) => {
  // console.log('@Head', methodName, parameterIndex, fieldName);
  if (!target[`paramFor${methodName}`]) target[`paramFor${methodName}`] = []
  target[`paramFor${methodName}`][parameterIndex] = !fieldName ? ['params'] : ['params', fieldName];
}
